package ldh.im.fxgui.controller;

import com.fluxvend.svgfx.SvgImageView;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.geometry.Pos;
import javafx.scene.Node;
import javafx.scene.control.Label;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.Pane;
import javafx.scene.layout.VBox;
import ldh.im.fxbase.component.VideoView;
import ldh.im.fxbase.data.pojo.ImUser;
import ldh.im.fxbase.util.*;
import ldh.im.fxgui.handle.WebRtcClient;
import ldh.im.fxgui.handle.WebRtcUiEvent;
import ldh.im.fxgui.util.UiUtil;
import ldh.im.fxgui.util.UserHeadImageUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.URL;
import java.util.ResourceBundle;
import java.util.Set;

// 视频聊天
public class WebRtcVideoController extends WebRtcBaseController implements Initializable, WebRtcUiEvent {

    private static final Logger LOGGER = LoggerFactory.getLogger(WebRtcVideoController.class);

    @FXML private SvgImageView videoSvgView;

    private boolean videoValue = true;

    public void setParams(String invitationUserId, String roomName, Set<String> userIdSet, double screenWidth,
                          double screenHeight) {
        this.invitationUserId = invitationUserId;
        this.roomName = roomName;
        this.isAccept = this.roomName != null;
        this.isAudio = false;

        if (userIdSet.size() == 1) {
            initP2pPane(userIdSet);
        } else {
            initGroupPane(userIdSet);
        }
        initUi();

        String loginUserId = UiUtil.getLoginImUser().getUserId();
        webRtcClient = new WebRtcClient(this, loginUserId, roomName, false, screenWidth, screenHeight);

        this.startSignalWebSocket(userIdSet, "视频聊天");

        this.playCallSound();
    }

    @Override
    public void exitRoom(String userId, boolean isReceiver) {
        super.exitRoom(userId, isReceiver);
    }

    @Override
    public void close() {
        super.close();
    }

    @Override
    public synchronized void receive(String userId, VideoView videoView) {
        LOGGER.info("receive webrtc connected success, userId: {}", userId);
        stopCallSound();

        Node node = userNodeViewMap.get(userId);
        VBox vBox = (VBox) node;
        vBox.getChildren().remove(0);
        vBox.getChildren().add(0, videoView);
        videoView.setStyle("-fx-background-color: black");
    }

    @Override
    public void localMediaCreated() {
//        if (!callSoundPlayed && !this.isAccept) {
//            this.playCallSound();
//            this.callSoundPlayed = true;
//        }
    }

    @FXML
    private void switchVideoEvent(MouseEvent event) {
        this.videoValue = !this.videoValue;
        if (this.videoValue) {
            this.videoSvgView.setSvg(this.getClass().getResource("/webrtc-img/camera.svg").toExternalForm());
        } else {
            this.videoSvgView.setSvg(this.getClass().getResource("/webrtc-img/camera_close.svg").toExternalForm());
        }
        this.webRtcClient.setVideoStatus(this.videoValue);
    }

    @Override
    public void initialize(URL url, ResourceBundle resourceBundle) {

    }

    @Override
    public Node getRoot() {
        return container;
    }

    private void initGroupPane(Set<String> userIdSet) {
        String loginUserId = UiUtil.getLoginImUser().getUserId();
        userIdSet.forEach(userId->{
            if (loginUserId.equals(userId)) return;
            Pane pane = createVideo(userId);
            flowPane.getChildren().addAll(pane);
        });
    }

    private void initP2pPane(Set<String> userIdSet) {
        Pane pane = createVideo(userIdSet.iterator().next());
        flowPane.getChildren().addAll(pane);
    }

    private Pane createVideo(String userId) {
        VBox vBox = new VBox();
        vBox.setAlignment(Pos.CENTER);
        ImageView imageView = new ImageView();
        imageView.setFitWidth(WebRtcClient.videoWidth);
        imageView.setFitHeight(WebRtcClient.videoHeight);
        ImUser user = ImCacheFactory.getInstance().getUser(userId);
        Image image = UserHeadImageUtil.getHeadImage(user.getHeadImg());
        imageView.setImage(image);

        Label label = new Label(user.getUserName());
        vBox.setSpacing(10);
        vBox.getChildren().addAll(imageView, label);

        userNodeViewMap.put(userId, vBox);
        return vBox;
    }
}
